<?php
namespace app\front\service;
use app\front\model\Temporary as TemporaryModel;
use app\front\model\Pondrecord as PondrecordModel;
use app\front\model\Sharehongbao as SharehongbaoModel;
use app\front\model\Store as StoreModel;
use app\front\model\Shop as ShopModel;
use app\front\model\Order as OrderModel;
use app\front\model\Account as AccountModel;
use app\front\model\Filiale as FilialeModel;
use app\front\model\Userinfo as UserinfoModel;
use app\front\model\Awardrecord as AwardrecordModel;
use app\front\model\WithdrawMember as WithdrawMemberModel;
use app\front\model\WithdrawOrder as WithdraworderModel;
use app\front\model\Orderstatistics as OrderStatisticsModel;
class GetMsgService{
    
   
    
    /**
    * 函数用途描述 :检查一分钟内是否有提现记录
    * @date: 2018年6月15日 上午8:45:25
    * @author: 孙洪亮
    * @param:  提现人姓名
    * @return: 有记录True 没 FALSE
    */
    public function checkWithdraw($name){
        $starttime = mktime(date('H'),date('i'),date('s')-57, date('m'),date('d'),date('Y'));
        $endtime = mktime(date('H'),date('i'),date('s'), date('m'),date('d'),date('Y'));
        $res= WithdraworderModel::where("create_time >='$starttime' and create_time <='$endtime'")->where('name',$name)->where('status',0)->select();
        $res= json_decode(json_encode($res),true);
        if(count($res)>1){
          return true;
      }else{
          return false;
      }
    }
    
    public function insertStatistics($j,$filiale_data,$MonthTurnover,$income){
        $month='';
        switch ($j) {
            case 1: $month='January'; break;
            case 2: $month='February'; break;
            case 3: $month='March'; break;
            case 4: $month='April'; break;
            case 5: $month='May'; break;
            case 6: $month='June'; break;
            case 7: $month='July'; break;
            case 8: $month='August'; break;
            case 9: $month='September'; break;
            case 10: $month='October'; break;
            case 11: $month='November'; break;
            case 12: $month='December'; break;
            default:
                ;
                break;
        }
        
        $StatisticsData=[
            'filiale_id'=>$filiale_data['id'],
            'filiale_name'=>$filiale_data['filiale_name'],
            'year'=>date('Y'),
            $month=>$MonthTurnover,
            'income'=> $income
        ];
        $isExist=OrderStatisticsModel::where('filiale_id',$filiale_data['id'])->find();
        if($isExist!=null){
            $where=[
                'filiale_id'=>$filiale_data['id']
            ];
            OrderStatisticsModel::update($StatisticsData,$where);
        }else{
            OrderStatisticsModel::create($StatisticsData);
        }
        
        
    }
    
    /**
    * 函数用途描述 :获得所有分公司信息
    * @date: 2018年6月11日 下午4:55:40
    * @author: 孙洪亮
    * @param:  null
    * @return: $filiale_data
    */
    public function getAllFilialeMsg(){
        $filiale_data = FilialeModel::where('delete_time is  NULL')->select();
        $filiale_data= json_decode(json_encode($filiale_data),true);
        return  $filiale_data;
    }
    
    /**
     * 函数用途描述 :根据分公司ID获得本公司某月营业额
     * @date: 2018年6月11日 下午3:56:33
     * @author: 孙洪亮
     * @param:  $filiale_id
     * @return: $ThisMonthTurnover(某月营业额）
     */
    public function GetThisMonthTurnover($filiale_id,$queryMonth=null,$queryYear=null){
        $ThisMonthOrder=$this->getThisMonthOrder($filiale_id,$queryMonth,$queryYear);
        $ThisMonthTurnover=0;
        for($i=0;$i<count($ThisMonthOrder);$i++){
           // $ThisMonthTurnover+=$ThisMonthOrder[$i]['money'];
            $ThisMonthTurnover=bcadd( $ThisMonthTurnover,$ThisMonthOrder[$i]['filiale_money'],3);
        }
        return  $ThisMonthTurnover;
    }
    
    /**
    * 函数用途描述 :获取特定分公司特定月份订单（默认本月）
    * @date: 2018年6月11日 下午3:39:15
    * @author: 孙洪亮
    * @param:  分公司ID，要查询的月份$queryMonth
    * @return: 返回二维数组
    */
    public function getThisMonthOrder($filiale_id,$queryMonth=null,$queryYear=null){
        if($queryMonth!=null){
           // $year=$queryYear;
            $month=$queryMonth;
        }else{
            //$year=date('Y');
            $month=date('m');
        }
         //设置年份
        if($queryYear!=null){$year=$queryYear;}else{$year=date('Y');}
        $starttime = mktime(date('H'),date('i'),date('s'), $month,date('d'),$year);
        $endtime = mktime(date('H'),date('i'),date('s'), $month+1,date('d')-date('d'),$year);
        $starttime= date("Y-m-01 00:00:00",$starttime);  
        $endtime= date("Y-m-d 23:59:59",$endtime);
        $res= OrderModel::where("create_time >='$starttime' and create_time <='$endtime'and filiale_id=$filiale_id")->select();
        $res= json_decode(json_encode($res),true);
        return $res;
    }
    
    public function TodayTaskPayNum(){
        $openid=$this->getOpenId();
        $starttime = strtotime(date("Y-m-d 00:00:00"));
        $starttime= date("Y-m-d H:i:s",$starttime);
        $endtime = strtotime(date("Y-m-d 23:59:59"));
        $endtime= date("Y-m-d H:i:s",$endtime);
        $starttime=strtotime($starttime);
        $endtime=strtotime($endtime);
        return count(WithdraworderModel::where("create_time >='$starttime' and create_time <='$endtime'and weixin='$openid'")->select());
    }
    
    public function getMemberTodayWithdrawNum(){
        $openid=$this->getOpenId();
        $starttime = strtotime(date("Y-m-d 00:00:00"));
        $starttime= date("Y-m-d H:i:s",$starttime);
        $endtime = strtotime(date("Y-m-d 23:59:59"));
        $endtime= date("Y-m-d H:i:s",$endtime);
      return count(WithdrawMemberModel::where("payment_time >='$starttime' and payment_time <='$endtime'and openid='$openid'")->select());
    }
    
    public function getFloatBaseRadPack($award_money,$RadPackFloat){
        $RadPackFloat=$RadPackFloat/100;
        $award_money= rand(bcmul($award_money*100, (1-$RadPackFloat),2),bcmul($award_money*100,(1+$RadPackFloat),2));
      return  $award_money= bcdiv( $award_money, 100,2);
    }
    
    public function changeFilialeHb($TemporaryMsg){
        //获取分公司信息
     
        $filiale_data = FilialeModel::where('id='.$TemporaryMsg['filiale_id'])->find();
        if($filiale_data['hbmoney']>=$TemporaryMsg['redpack']){
            $hbmoney['hbmoney'] = bcsub($filiale_data['hbmoney'], $TemporaryMsg['redpack'],2);
            FilialeModel::startTrans();
            if(FilialeModel::where('id='.$filiale_data['id'])->update($hbmoney)>0){
                FilialeModel::commit();
            }else{
                FilialeModel::rollback();
            }
    }
    }
    
    public function changeShopHb($TemporaryMsg){
        //获取分公司信息
        $shop_data =  ShopModel:: where('id='.$TemporaryMsg['shop_id'])->find();
        if($shop_data['shop_hb_money']>=$TemporaryMsg['redpack']){
            $hbmoney['shop_hb_money'] = bcsub($shop_data['shop_hb_money'], $TemporaryMsg['redpack'],2);
            $hbmoney['id']=$shop_data['id'];
            ShopModel::startTrans();
            if(ShopModel::update($hbmoney)){
                ShopModel::commit();
            }else{
                ShopModel::rollback();
            }
        }
    }
    
    public function insertRadPack( $TemporaryMsg){
        $filiale_data = FilialeModel::where('id',$TemporaryMsg['filiale_id'])->find();
        $record_data = ['mch_billno'=> $TemporaryMsg['out_trade_no'],'customer_id'=>$TemporaryMsg['open_id'],
            'shop_id'=>$TemporaryMsg['shop_id'],'filiale_id'=>$TemporaryMsg['filiale_id'],'store_id'=>$TemporaryMsg['store_id'],
            'order_money'=>($TemporaryMsg['total_fee']/100),'award_money'=>$TemporaryMsg['redpack'],'create_time'=>date("Y-m-d H:i:s",time ()),
            'record_statu'=>$TemporaryMsg['record_statu'],'purpose'=>$TemporaryMsg['purpose']];
        AwardrecordModel::create($record_data);
    }
    
    public function insertWithdrawMember($userMsg,$result,$WithdrawMoney){
        $userMsg['money']=$WithdrawMoney;
        unset($userMsg['id']);
        unset($userMsg['headimgurl']);
        if(!is_array($result)){
            $userMsg['payment_time']=date("Y-m-d H:i:s",time());
            $userMsg['desc']=$result;
            $userMsg['result_code']='Fail';
        }else{
            $userMsg['return_code']=$result['return_code'];
            $userMsg['result_code']=$result['result_code'];
            $userMsg['partner_trade_no']=$result['partner_trade_no'];
            $userMsg['status']=1;
            $userMsg['payment_time']=$result['payment_time'];
            $userMsg['desc']='提现成功';
        }
        WithdrawMemberModel::create($userMsg);    
    }
    
    public function getWithdrawForOpenid($openid){
        $WithdrawMsg= WithdrawMemberModel::where('openid',$openid)->field('money,payment_time,desc')->order('payment_time desc')->select();
        return $WithdrawMsg; 
    }
    
    public function getRecordForOpenid($openid){
     $RedPackMsg= AwardrecordModel::where('customer_id',$openid)->where('award_money>=0.01')->field('store_id,create_time,award_money')->order('create_time desc')->select();
     return $RedPackMsg;
    }
    
    /**
     * 函数用途描述 :获取当前用户openid
     * 特别提示：此方法较逻辑较为复杂分，且后期发现无法正常使用于是针对本环境进行了更改，所以不可作为基础方法直接复制应用
     * 此方法较为依赖session 耦合性并不符合我的预期，将来重构建议进行优化如有疑问请联系方法编码者
     * @date: 2018年2月6日 上午9:12:54
     * @author: 孙洪亮
     * @param:  null
     * @return: null
     */
    public function getOpenId(){
        if(session('openid')!=null){
            //  $this->logs("getopenid.txt", date("Y-m-d H:i:s",time())."if"."openid=".$_SESSION['openid']."||") ;
            return session('openid');
        }else{
            //1.用户访问一个地址 先获取到code
            if(input('param.code')==null){
                //print_r($_SERVER);
               // $redurl = config('gahPayURL');//$_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                // $redurl ='http://www.zfshlm.com/155e7ac5857fb33bb5d9430ef3be1699/GongZhongHaoPay/Index/WeiXinPay.php';
                $REQUEST_URI=substr($_SERVER['REQUEST_URI'],1);
                $redurl = $_SERVER['REQUEST_SCHEME'] . '://' . config('HTTP_HOST') . $REQUEST_URI;
                $url = config('CODEURL') . "appid=" .config('appid') ."&redirect_uri={$redurl}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
                //构建跳转地址 跳转
                //  $this->logs("getopenid.txt", date("Y-m-d H:i:s",time())."url=".$url."<br>") ;
                //logs("test.txt", $url); 
                header("location:{$url}");exit;
              
            }else{
                //2.根据code获取到openid
                //调用接口获取openid
                $openidurl = config('OPENIDURL') . "appid=" . config('appid') . "&secret=".config('appsecret') . "&code=" .input('param.code')  . "&grant_type=authorization_code";
                $data = file_get_contents($openidurl);
                $arr = json_decode($data,true);
                logs("openid.txt", $arr);
                session('openid',$arr['openid'])  ;
                return $arr['openid'];
            }
        }
        
    }
    
    /**
     * 函数用途描述 :获取门店ID
     * @date: 2018年1月18日 上午10:59:20
     * @author: 孙洪亮
     * @param: $store_name(商家名称)
     * @return: store_id(商家ID)
     */
    
    public function getStoreIdForStoreName($store_name){
        $store_name="'".$store_name."'"; //拼写字符串格式
        $store= StoreModel::where('store_name='. $store_name)->where('status is NULL')->field('id')->find();
        $id= $store['id'];//查询数组第一个元素id
        return $id;
    }
    
    
    /**
     * 函数用途描述 : 将临时信息存储到表中
     * @date: 2018年1月20日 上午10:41:34
     * @author: 孙洪亮
     * @param:
     * @return:
     */
    public function Temporary_add($out_trade_no,$openid,$store_id,$store_name,$total_fee,$redpack,$shop_id,$filiale_id,$record_statu,$purpose){
        $temporar_data = [
            'out_trade_no'=>$out_trade_no,
            'open_id'=>$openid,
            'store_id'=>$store_id,
            'store_name'=>$store_name,
            'total_fee'=>$total_fee,
            'redpack'=>$redpack,
            'create_time'=>date("Y-m-d H:i:s",time()),
            'shop_id'=>$shop_id,
            'filiale_id'=>$filiale_id,
            'record_statu'=>$record_statu,
            'purpose'=>$purpose
        ];
        $res=TemporaryModel::create($temporar_data);
    }
    
    /**
     * 函数用途描述 :判断用户信息是否已存在在用户表
     * @date: 2018年1月19日 上午10:32:30
     * @author: 孙洪亮
     * @param: $mch_billno（订单号）
     * @return:返回订单金额
     */
    public  function existUserinfo($openid){
        $openid="'".$openid."'";
        $Userinfo = UserinfoModel::where('openid='.$openid)->field('id,openid,nickname,money,headimgurl')->find();
        $Userinfo = json_decode($Userinfo,true);  
        return  $Userinfo;
    }
    
    
    /**
     * 函数用途描述 : 存储用户信息到数据库中
     * @date: 2018年1月18日 下午3:35:32
     * @author: 孙洪亮
     * @param: $openid
     * @return: null
     */
    public  function saveUserInfo($openid){
        //base64_encode();
        $userInfo['nickname']="";
        $userInfo= getMemberMessageForOpenid($openid);
        $userInfo['create_time']=date("Y-m-d H:i:s",time());
        $userInfo['attention_time']=$userInfo['create_time'];
        $userInfo['money']=0;
      //  logs("userinfofofof.txt",$userInfo);
        if($userInfo['subscribe']==0){
            $userInfo['nickname']='非会员用户';
        }
        
        UserinfoModel::create($userInfo);
        
    }
    
    
    /**
     * 函数用途描述 :更改用户信息到数据库中
     * @date: 2018年1月28日 下午6:06:45
     * @author: 孙洪亮
     * @param: $openid
     * @return:null
     */
    public  function updateUserInfo($openid){
        $userInfo= getMemberMessageForOpenid($openid);
       $user= $this->existUserinfo($openid);
        $userInfo['id']=$user['id'];
        $userInfo['create_time']=date("Y-m-d H:i:s",time());
        if($userInfo['subscribe']==0){
            $userInfo['nickname']='非会员用户';
        }
        UserinfoModel::update($userInfo);
    }

    public  function updateUserMoney($userMsg){
        
        $res=UserinfoModel::update($userMsg);
    
    }
    
    /**
     * 函数用途描述 : 判断用户今天是否领过红包
     * @date: 2018年2月3日 上午1:03:22
     * @author: 孙洪亮
     * @param:
     * @return:
     */
    public function TodayisExistShareHongBao($openid){
        $isExist=0;
        $starttime = strtotime(date("Y-m-d 00:00:00"));
        $starttime= date("Y-m-d H:i:s",$starttime);
        $endtime = strtotime(date("Y-m-d 23:59:59"));
        $endtime= date("Y-m-d H:i:s",$endtime);
        $res=  SharehongbaoModel::where("create_time >='$starttime' and create_time <='$endtime'")->select();
        foreach( $res as $v )
        { //存在且金额大于0.3才算有效分享
            if(strcmp($openid,$v['openid'])==0){
                if($v['money']>=0.3){
                    $isExist=1;
                    break;
                }
                
            }
        }
        
        return $isExist;
        
    }
    
    public function getRedpackMsgForID($mch_billno){
        $RedPackMsg= AwardrecordModel::where('mch_billno',$mch_billno)->field('customer_id,store_id,order_money,award_money')->find();
        return $RedPackMsg;
    }
    
    public function getOrderMsgForID($mch_billno){
        $orderMsg= OrderModel::where('id',$mch_billno)->field('customer_id,store_id,money,shop_money,shop_id,filiale_id')->find();
        return $orderMsg;
    }
    
    public function getTodayOrder( $store_id){
        $starttime = strtotime(date("Y-m-d 00:00:00"));
        $starttime= date("Y-m-d H:i:s",$starttime);
        $endtime = strtotime(date("Y-m-d 23:59:59"));
        $endtime= date("Y-m-d H:i:s",$endtime);
        $Orders= OrderModel::where("create_time >='$starttime' and create_time <='$endtime'and store_id=$store_id")->select();
        return $Orders;
        //带着参数跳转到gzhPay.html
    }
    
    public function getUserinfoForOpenid($openid){
        return UserinfoModel::where('openid',$openid)->field('id,nickname,subscribe,shareNum,money')->find();
    }
    
    public function getStoreForStoreid($store_id){
        return StoreModel::where('id',$store_id)->where('status is NULL')->field('store_name,imgurl,phone,address,shop_id')->find();
    }
    /*
     *  'out_trade_no'=>$out_trade_no,
            'open_id'=>$openid,
            'store_id'=>$store_id,
            'store_name'=>$store_name,
            'total_fee'=>$total_fee,
            'redpack'=>$redpack,
            'create_time'=>date("Y-m-d H:i:s",time()),
            'shop_id'=>$shop_id,
            'filiale_id'=>$filiale_id,
            'record_statu'=>$record_statu,
            'purpose'=>$purpose
            ->field('out_trade_no,open_id,store_id,total_fee,store_name,redpack,create_time,shop_id,filiale_id,record_statu')
     */
    public function getTemporaryForMchId($mch_billno){
     return TemporaryModel::where('out_trade_no',$mch_billno)->find();
    }
    
    public function order_add($order_id,$customer_id,$store_id,$money,$status,$desc, $redpack)
    {
        $store_data  =  StoreModel::where('id='.$store_id)->find();
        $shop_data  =  ShopModel::where('id='.$store_data['shop_id'])->find();
        $filiale_data  =  FilialeModel::where('id',$shop_data['filiale_id'])->find();
        $account_data =  AccountModel::where('shop_id='.$shop_data['id'])->find();
        if($account_data==null){
            $account_data =  AccountModel::where('shop_id=0 and filiale_id='.$filiale_data['id'])->find();
        }
        $filiale_data= json_decode($filiale_data,true);
        $pond_money=bcmul($money,bcdiv( $account_data['enter_pond_rete'],100,3),3);
        $filiale_data['hbmoney']= bcadd($filiale_data['hbmoney'], $pond_money,3);
        FilialeModel::update($filiale_data);
        $ordmoney= $money;
       $money= bcsub($money, $pond_money,3);
        $order_data = [
            'id'=>$order_id,
            'customer_id'=>$customer_id,
            'money'=>$ordmoney,
            'store_id'=>$store_id,
            'shop_id'=>$shop_data['id'],
            'filiale_id'=>$filiale_data['id'],
            'create_time'=>date("Y-m-d H:i:s",time()),
            'status'=>1,
            'shop_money'=>bcmul($money,bcdiv($account_data['shop_percent'],100,2),2),
            'company_money'=>bcmul($money,bcdiv($filiale_data['server_money'],100,2),2),
            'filiale_money'=>bcmul($money,bcdiv($account_data['server_percent'],100,2),2),
            'pond_money'=>$pond_money,
            'investor_money'=>bcmul($money,bcdiv($account_data['investor_percent'],100,2),2),
            'desc'=>$desc,
            'msg'=>1,
            'redpack'=> $redpack
        ];
        if($pond_money>0){
            $this->pondRecordAdd($filiale_data['id'],$ordmoney, $customer_id, $pond_money, $store_data['store_name']);
       }
        OrderModel::create($order_data);
    }
    
    public function pondRecordAdd($filiale_id,$money,$customer_id,$pond_money,$store_name){
        $nickname= $this->getUserinfoForOpenid($customer_id)['nickname'];
        $pondRecord_data = [
            'filiale_id'=>$filiale_id,
            'nickname'=>$nickname,
            'money'=>$money,
            'store_name'=>$store_name,
            'create_time'=>date("Y-m-d H:i:s",time()),
            'pond_money'=>$pond_money
        ];
       PondrecordModel::create($pondRecord_data);
    }
   
}

